package org.yanfengying.org.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.yanfengying.car.query.CarSearchQuery;
import org.yanfengying.car.service.ICarSearchServiceImpl;
import org.yanfengying.es.doc.CarDoc;
import org.yanfengying.es.repository.CarDocRepository;
import org.yanfengying.utils.PageList;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Service
public class CarSearchServiceImplImpl implements ICarSearchServiceImpl {

    @Autowired
    private CarDocRepository carDocRepository;

    @Override
    public PageList search(CarSearchQuery query) {
        //创建querybuilder对象
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();

        //高级查询-关键字查询-过滤查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(StringUtils.isNoneBlank(query.getKeyword())){
            boolQuery.must(QueryBuilders.multiMatchQuery(query.getKeyword(), "title","shopName","typeName","carInfo"));
        }

        Long typeId = query.getTypeId();//类型
        Integer costeffective = query.getCosteffective();//是否超值
        Integer rushsale = query.getRushsale();//急售
        Integer quasinewcar = query.getQuasinewcar();//是否是准新车
        Integer transitivecountry = query.getTransitivecountry();//可迁全国
        if(typeId != null){
            boolQuery.filter(QueryBuilders.termQuery("typeId", typeId));
        }
        if(costeffective != null){
            boolQuery.filter(QueryBuilders.termQuery("costeffective", costeffective));
        }
        if(rushsale != null){
            boolQuery.filter(QueryBuilders.termQuery("rushsale", rushsale));
        }
        if(quasinewcar != null){
            boolQuery.filter(QueryBuilders.termQuery("quasinewcar", quasinewcar));
        }
        if(transitivecountry != null){
            boolQuery.filter(QueryBuilders.termQuery("transitivecountry", transitivecountry));
        }
        //价格区间过滤
        BigDecimal maxPrice = query.getMaxPrice();
        BigDecimal minPrice = query.getMinPrice();
        if(maxPrice != null){
            boolQuery.filter(QueryBuilders.rangeQuery("costprice").lte(maxPrice));
        }
        if(minPrice != null){
            boolQuery.filter(QueryBuilders.rangeQuery("costprice").gte(minPrice));
        }
        //车龄->(当前时间-上牌时间)
        Integer carAge = query.getCarAge();
        Integer carAgeType = query.getCarAgeType();//0->以下 1-以上
        if(carAge != null && carAgeType != null){
            carAge = 0 - carAge;//拿到车龄的负数->创建一个时间用于计算车龄
            Date date = DateUtils.addYears(new Date(), carAge);
            if(carAgeType == 0){//向下取值
                boolQuery.filter(QueryBuilders.rangeQuery("reigstertime").gte(date));
            }else if (carAgeType == 1){
                //向上取值
                boolQuery.filter(QueryBuilders.rangeQuery("reigstertime").lte(date));
            }
        }
        builder.withQuery(boolQuery);
        //排序查询->获取排序字段->获取排序方式->返回排序结果
        String sortType = query.getSortType();//排序方式
        String sortField = query.getSortField();//要排序的字段
        SortOrder sortOrder = SortOrder.DESC;//默认排序为倒序排序
        if("asc".equals(sortType)){
            sortOrder = SortOrder.ASC;//更改排序方式为正序
        }
        //判断排序字段
        if("jg".equals(sortField)){
            builder.withSort(SortBuilders.fieldSort("costprice").order(sortOrder));

        }else if("lc".equals(sortField)){
            builder.withSort(SortBuilders.fieldSort("mileage").order(sortOrder));

        }else if("cl".equals(sortField)){
            builder.withSort(SortBuilders.fieldSort("reigstertime").order(sortOrder));

        }else if("zxfb".equals(sortField)){
            builder.withSort(SortBuilders.fieldSort("onsaletime").order(sortOrder));
        }

        //分页->当前页,每页条数
        builder.withPageable(PageRequest.of(query.getPage()-1, query.getPageSize()));

        //从es中查询目标数据
        Page<CarDoc> carDocs = carDocRepository.search(builder.build());
        List<CarDoc> content = carDocs.getContent();//当前页数据
        Long totalElements = carDocs.getTotalElements();//总条数
        //Integer.parseInt(totalElements+"")  类型强转
        return new PageList(Integer.parseInt(totalElements+""),content);
    }
}
